package com.fyt.reachgo.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 基于redis的分布式锁实现类
 */
public class SimpleRedisLock implements Lock{

    // 注入redis操作模板
    private final StringRedisTemplate stringRedisTemplate;
    // 锁的名称
    private final String name;
    // 锁的key
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    /**
     * 尝试获取锁
     * @param timeoutSec
     * @return true:获取锁成功，false:获取锁失败
     */
    @Override
    public boolean lock(Long timeoutSec) {
        // 获取锁的key
        String key = KEY_PREFIX + name;
        // 获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(key, threadId, timeoutSec, TimeUnit.SECONDS);
        // 拆箱并返回获取锁的成功标志
        return Boolean.TRUE.equals(success);
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock() {
        // 获取锁的key
        String key = KEY_PREFIX + name;
        // 获取锁中的线程标识
        String id = stringRedisTemplate.opsForValue().get(key);
        // 获取本身线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 如果线程标识一致，则删除锁
        if (threadId.equals(id)) {
            stringRedisTemplate.delete(key);
        }
    }
}























